package com.shopping.servlets;

import com.shopping.dao.UserDao;
import com.shopping.dao.impl.UserDaoImpl;
import com.shopping.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 处理用户的注册请求
 * 实现步骤：
 *     1.获取客户端提交的数据
 *     2.创建处理类对象并调用处理添加用户方法实现功能
 *     3.根据处理结果进行页面跳转
 * */
@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            request.setCharacterEncoding("UTF-8");
            String user_name = request.getParameter("user_name");
            String user_password = request.getParameter("user_password");
            Integer user_sex = Integer.parseInt(request.getParameter("user_sex"));
            String user_email = request.getParameter("user_email");
            String birthday = request.getParameter("user_birthday");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date user_birthday = format.parse(birthday);

            String user_address = request.getParameter("user_address");

            String[] hobbyArr = request.getParameterValues("user_hobbys");
            StringBuffer user_hobbys = new StringBuffer();
            for(String hobby : hobbyArr){
                user_hobbys.append(hobby).append("_");
            }
            user_hobbys.delete(user_hobbys.length()-1,user_hobbys.length());

            //将客户端获得的数据封装到User对象中
            User user = new User();
            user.setUser_address(user_address);
            user.setUser_birthday(user_birthday);
            user.setUser_email(user_email);
            user.setUser_hobbys(user_hobbys.toString());
            user.setUser_name(user_name);
            user.setUser_password(user_password);
            user.setUser_sex(user_sex);
            UserDao userDao = new UserDaoImpl();
            int num = userDao.addUser(user);
            if(num>0){
                //跳转到index.jsp
                response.sendRedirect("index.jsp");
            }else{
                response.sendRedirect("register.html");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
